package my.data.x.service;


import my.data.x.dao.JobMapper;
import my.data.x.exception.XErrorCode;
import my.data.x.exception.XException;
import my.data.x.job.thread.ThreadPool;
import my.data.x.model.Job;
import my.data.x.util.JobStatus;
import my.data.x.util.XSeqGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JobService {
    @Autowired
    private JobMapper jobMapper;
    @Autowired
    private XSeqGen xSeqGen;
    @Autowired
    private ThreadPool threadPool;
    public List<Job> getJobService(){
        return jobMapper.selectJobs();
    }
    public long genJobId(){
        return xSeqGen.getID();
    }

    public int newJob(String name,String config) throws Exception{
        int isExists=jobMapper.selectJobFromName(name);
        if(isExists==0){
            Job job=new Job();
            job.setId(genJobId());
            job.setName(name);
            job.setConfig(config);
            job.setStart_mode(1);
            job.setStatus(1);
            job.setSchedule("");
            return jobMapper.insertJob(job);
        }else {
            Job job=new Job();
            job.setName(name);
            job.setConfig(config);
            return jobMapper.updateJob(job);
        }

    }

    public int deleteJob(Long job) throws Exception{
        return jobMapper.deleteJob(job);
    }


    public String getJobConfig(long jobid) throws Exception {
        return jobMapper.getJobById(jobid).getConfig();
    }
    public String getJobStatus(long jobid) throws Exception{
        return JobStatus.getStatus(jobMapper.getJobById(jobid).getStatus());
    }
    public int jobStart(long jobid) throws Exception {
        Job job=jobMapper.getJobById(jobid);
        if(job.getStatus()==JobStatus.getStatusTag(JobStatus.RUNNING)){
            throw new XException(XErrorCode.RUNTION_ERROR,String.format("当前任务正在执行，任务状态是：%s",JobStatus.getStatus(job.getStatus())));
        }
        threadPool.addThread(job);

        return 1;
    }

    public int setJobStatus(Job job) throws Exception{
        return jobMapper.updateJobStatusById(job);
    }
    public Job getJobByid(long jobid) throws Exception{
        return jobMapper.getJobById(jobid);
    }
}
